let model = require('../model/model.js');
const fs=require('fs')
const path=require('path')
const moment = require('moment')
let  articleController={};
let statusmap={
    0:"<span class='c-ccc'>待审核</span>",
    1:"<span class='c-green'>审核通过</span>",
    2:"<span class='c-red'>审核失败</span>"
}
articleController.index = (req,res)=>{
    let sql ='select t1.*,t2.classify FROM `article mark` t1 LEFT JOIN cate t2 on t1.classify2=t2.article_id where t1.is_delete=0 order by t1.add_time desc'
    model(sql).then(rows=>{
        rows.map(item=> item.statu3=statusmap[item.status])

        let User= JSON.parse(req.session.userInfo)
        
           res.render('art.html',{Userinfo:User})
          
       })
   
};
articleController.index2 = (req,res)=>{
    let sql ='select t1.*,t2.classify FROM `article mark` t1 LEFT JOIN cate t2 on t1.classify2=t2.article_id where t1.is_delete=0 order by t1.add_time desc'
    model(sql).then(rows=>{
        rows.map(item=> item.statu3=statusmap[item.status])
        let User= JSON.parse(req.session.userInfo)
           res.render('art2.html',{articles:rows,Userinfo:User})
       })
   
};
articleController.recyclework=(req,res)=>{
    let sql ='select t1.*,t2.classify FROM `article mark` t1 LEFT JOIN cate t2 on t1.classify2=t2.article_id where t1.is_delete=1 order by t1.add_time desc'
    model(sql).then(rows=>{
        rows.map(item=> item.statu3=statusmap[item.status])
           res.render('recycle.html',{articles:rows})
       })

}
articleController.articleCount=async(req,res)=>{

   let {  curr=1 ,limit=8,intEle,selEle}= req.query
   let where = '';
   if(intEle){
    where+= ` and title like '%${intEle}%'`
   }
   if(selEle){
    where += ` and status = ${selEle}`
}
    console.log(where )
   let offset =(curr -1)*limit
   let sql = 'select count(*) as count from  `article mark`   where is_delete = 0 '+where;
   let result =await model(sql)
   let sql2 ='select t1.*,t2.classify FROM `article mark` t1 LEFT JOIN cate t2 on t1.classify2=t2.article_id where t1.is_delete=0  '+where+' order by t1.add_time desc limit '+offset+','+limit;
    console.log(curr,limit)
    let result2 =await model(sql2)
    result2.map(item=> item.statu3=statusmap[item.status])
    res.json({ count:result[0].count, data:result2 })
   
}
articleController.add=(req,res)=>{
    
    // let {fo_title,fo_cat,fo_author,fo_content} = req.body;
    let {  fo_title,fo_cat,fo_author,fo_content}=req.body;
    let winurl="";
    if(req.file){
        let{ originalname,filename,destination}=req.file;
        let ext=originalname.substring(originalname.indexOf('.'));
    
        let oldPath =path.join(__dirname,"../",destination,filename);
    
        let newPath=path.join(__dirname,"../",destination,filename)+ext;
        // console.log(oldPath)
        // console.log(newPath)
        fs.renameSync(oldPath,newPath);
        winurl=destination+filename+ext;
    }
    var  sql = 'INSERT INTO `article mark`(title,content,author,classify2,img_url) VALUES(?,?,?,?,?)';
    var  bind = [fo_title,fo_content,fo_author,fo_cat,winurl]; 
    console.log(bind)
    if(bind.indexOf("") !=0 ){
        model(sql,bind).then(rows=>{
           
            console.log("添加成功!")
            res.json({status:20000,message:"修改成功"})
        }).catch( err=>{   throw err}); 
    }
  
}




articleController.recycle=(req,res)=>{
    let { id,} = req.query;
    // let sql = "delete from `article mark` where art_id= ?";
    let sql ="UPDATE `article mark` SET is_delete=1 WHERE art_id=?"
    var  bind = [id];
    // console.log(bind)
    model(sql,bind).then( res.send("接收了")).catch(err=>{
        if(err){
            throw err;
        }
       
  });
   
}
articleController.Reback=(req,res)=>{
    let { id,} = req.query;
    // let sql = "delete from `article mark` where art_id= ?";
    let sql ="UPDATE `article mark` SET is_delete=0 WHERE art_id=?"
    var  bind = [id];
    // console.log(bind)
    model(sql,bind).catch(err=>{
        if(err){
            throw err;
        }
       
  });
    res.redirect('/recyclework')
}
articleController.dele=(req,res)=>{
    let { id,url} = req.query;
    let sql = "delete from `article mark` where art_id= ?";
   
    var  bind = [id];
    // console.log(bind)
    model(sql,bind).then(result =>{
    let oldpath=path.join(__dirname,'../',url)
    fs.unlink(oldpath,()=>{ console.log( "成功删除"+url)})
  }).catch(err =>{ throw err}) ;
    res.redirect('/')
}
//获取编辑内容
articleController.inquiry=(req,res)=>{
    let {edit_id} = req.query;
    let sql="select t1.*,t2.classify FROM `article mark` t1 LEFT JOIN cate t2 on t1.classify2=t2.article_id where art_id =?";
    let sql2= `select article_id,classify FROM cate`;
    let bind =[edit_id];
    let fist= model(sql,bind)
    let second= model(sql2)
    Promise.all([fist,second]).then(result =>{
        res.json({ artitem:result[0][0], catData:result[1]})
    })
    
}
articleController.getCate=(req,res)=>{
    let sql= `select article_id,classify FROM cate`;
    model(sql).then(result => { res.json( { result }) })
}
//分类列表
articleController.classify=(req, res)=>{
 
    let sql="SELECT * FROM cate ";
    model(sql).then(rows=>{
    //    console.log(rows) //数组
       let str="";
       rows.forEach(item => str +=`SUM(IF(classify2 = ${item.article_id}, 1, 0))  AS "${item.article_id}",`)
      str +=`SUM(IF(classify2= 0, 1, 0)) AS status0`;
        let result=rows;
        let sql2="SELECT COUNT(*) AS total,	"+str+" FROM `article mark` "
        model(sql2).then(rows=>{
            let result2=rows[0];
            result.map(item => {
                  item.sum= result2[item.article_id]
            })
          res.render("classify.html",{classify : result,total: result2.total,cateDefind:result2.status0})
        
        }).catch(err =>{ console.log("数据库出错")})
    }).catch(err =>{ console.log("数据库出错")})
}
//删除分类条
articleController.deleteCate=((req,res)=>{
    console.log(req.body)
    let {edit_id} = req.body
    console.log(edit_id)
 let sql ="delete from cate where article_id="+edit_id

 model(sql).then(result =>  res.json( { status :20000 ,message:"删除成功" } ))

})
//更新分类条 
articleController.updataClassify =(req, res)=>{
    let {classify,ishide,article} =req.body;
    let sql2=`SELECT * FROM cate WHERE classify="${classify}" and article_id !=${article}`
    let sql = `UPDATE cate SET classify="${classify}", ishide = "${ishide}" WHERE article_id=${article}`
    model(sql2).then(result =>{
        if(result.length){
            res.json({ status: -2,message:"该分类已存着"})
        }else{
            model(sql).then(result =>{
                if(result.affectedRows){
                    res.json({ status : 20000 ,message :"修改成功"})
                }else{
                    res.json({ status : -1 ,message :"修改失败"})
                }
            })
        }
    })
}

//添加分类条
articleController.addClassify =(req, res)=>{
    let {classify,ishide} =req.body;
    console.log(moment().format())
    let sql2=`SELECT * FROM cate WHERE classify="${classify}"`
    let sql = `INSERT INTO cate(classify,ishide,updata) VALUES("${classify}","${ishide}","${moment().format()}")`
    model(sql2).then(result =>{
        if(result.length){
            res.json({ status: -2,message:"该分类已存着"})
        }else{
            model(sql).then(result =>{
                if(result.affectedRows){
                    res.json({ status : 20000 ,message :"添加成功"})
                }else{
                    res.json({ status : -1 ,message :"添加失败"})
                }
            })
        }
    })
}
//获取html内容
articleController.getContent= async (req, res)=>{
    let { art_id }=req.body;
    console.log(art_id);
    let sql="select t1.*,t2.classify FROM `article mark` t1 LEFT JOIN cate t2 on t1.classify2=t2.article_id where art_id ="+art_id;
      let data= await model(sql) 
      console.log(data)
      try{
        res.json({  status:20000, message:"获取成功",content:data[0].content})
      }catch(err){
        res.json({  status:-1, message:"获取失败"})
      }

}

//统计分类文章总数
articleController.cateArticleCount=async (req,res)=>{
let sql ='SELECT t2.classify,count(t1.classify2)as count  from `article mark` t1 LEFT JOIN cate t2 on t1.classify2 =t2.article_id GROUP BY t1.classify2'
 let result = await model(sql)
 console.log(result )
 res.json(result)


}



//编辑
articleController.update=(req, res) => {
    console.log(req.body)
    let {  fo_title,fo_cat,fo_author,fo_content,fo_status,fo_id,fo_url}=req.body;
    let sql = "update `article mark` set title =?,author=?,content=?,classify2=?,status=? where art_id =?";
    let bind = [fo_title,fo_author,fo_content,fo_cat,fo_status,fo_id];
    let oldpath=""
    if(req.file){
        let{ originalname,filename,destination}=req.file;
        let ext=originalname.substring(originalname.indexOf('.'));
    
        let oldPath =path.join(__dirname,"../",destination,filename);
    
        let newPath=path.join(__dirname,"../",destination,filename)+ext;
        fs.renameSync(oldPath,newPath);
       let winurl=destination+filename+ext;
         sql = "update `article mark` set title =?,author=?,content=?,classify2=?,status=?,img_url=? where art_id =?";
         bind = [fo_title,fo_author,fo_content,fo_cat,fo_status,winurl,fo_id];
          oldpath=path.join(__dirname,'../',fo_url)
        
    }
    model(sql,bind).then(result=>{
        if(result.affectedRows){
            fs.unlink(oldpath,()=>{})
        }
    })
    res.json({status:20000,message:"修改成功"})
}
module.exports=articleController;